var $j = jQuery.noConflict();
var urlsecurity = 'http://localhost:8080/service/Security.groovy';
var currentUsr;
var currentName;
var currentEmail;
var currentBirthDate;
var currentPass;
var currentToken;
var cookie;

checkResp = function(r) {
	if(r.getElementsByTagName('response')[0].getAttribute('status') == 'fail'){
		var msg;
		
		switch(r.getElementsByTagName('error')[0].getAttribute('code')) {
		case '1':
			displayAlert('Missing method');
			return false;
		case '2':
			displayAlert('Missing language id');
			return false;
		case '4':
			displayAlert('Missing username');
			return false;
		case '5':
			displayAlert('Missing password');
			return false;
		case '101':
			displayAlert('Invalid method');
			return false;
		case '102':
			displayAlert('Invalid language');
			return false;
		case '103':
			displayAlert('Invalid country');
			return false;
		case '104':
			displayAlert('Invalid user, please check your username and password');
			return false;
		case '105':
			//displayAlert('Please Login again');
			displayPopLogIn();
			return false;
		case '107':
			displayAlert('Invalid username');
		case '108':
			displayAlert('Invalid password');
		case '109':
			displayAlert('Invalid name');
		case '110':
			displayAlert('Invalid email');
		case '111':
			displayAlert('Invalid birth date');
		case '112':
			displayAlert('Invalid category id');
		case '201':
			displayAlert('User already exists');
			return false;
		case '999':
			displayAlert('Unespected error, please try later');
		case '13':
			displayAlert("Missing order id ");
		case '14':
			displayAlert("Missing address id");
		case '115':
			displayAlert("Invalid order id");
			default:
			displayAlert("Unknown error, please contact us");
		return false;
		}
	}
	
	return true;
};

signin = function(username, pass) {
	var resp;
	
	cookie = new cookiejar('tienda_virtual');
	currentPass = pass;
	currentUsr = username;
	
	var req = new Ajax.Request(urlsecurity, {
		method: 'post',
		parameters: {method: 'SignIn', username: username, password: pass},
		onSuccess: function(transport){
			resp = transport.responseXML;
			
			if(!checkResp(resp)){
					var logindiv = document.getElementById("loginLi");
					logindiv.setAttribute("onclick","logInClick();");
					logindiv.innerHTML="Login";	
					currentUsr = null;
					currentPass = null;
					currentToken = null;
			}else{
				currentToken = resp.getElementsByTagName('token')[0].firstChild.nodeValue;
				
				cookie.setCookie('username', currentUsr);
				cookie.setCookie('password', currentPass);
				cookie.setCookie('token', currentToken);
				cookie.write();
				
				var logindiv = document.getElementById("loginLi");
				//logindiv.innerHTML="<a id=\"loginLi\" onClick=\"logOut()\">Logout</a>";
				logindiv.setAttribute("onclick","logOut();");
				logindiv.innerHTML="Logout";	
			/*	var name = document.getElementById("Bienvenida");
				name.innerHTML = "Bienvenido \"" + currentUsr +"\"";*/
				/* Ahora habilito "Opciones Ocultas" */
				var a = document.getElementById("OrdenesButton");
				a.style.display="";
				var micuenta = document.getElementById("micuenta");
				micuenta.style.display="";
				
			}
		},
		onFailure: function(){ alert('Problems on Ajax Request')}
  });	
};

sigin = function(username, token, page) {
	var resp;
	var req = new Ajax.Request(urlsecurity, {
		method: 'post',
		parameters: {method: 'SignOut', username: username, authentication_token: token},
		onSuccess: function(transport){
			resp = transport.responseXML || "no response text";
			currentUsr = null;
			currentPass = null;
			currentToken = null;	
			/* Destoying Cookie */
			cookie = new cookiejar('tienda_virtual');
			cookie.setCookie('username', currentUsr);
			cookie.setCookie('password', currentPass);
			cookie.setCookie('token', currentToken);
			cookie.write();
			//
			var logindiv = document.getElementById("loginLi");
			logindiv.setAttribute("onclick","logInClick();");
			logindiv.innerHTML="Login";	

			var name = document.getElementById("Bienvenida");
			name.innerHTML = "Bienvenid@";
			document.location.href = page;
		},
		onFailure: function(){ alert('Problems on Ajax Request') }

  });
};

signout = function(username, token) {
	var resp;
	var req = new Ajax.Request(urlsecurity, {
		method: 'post',
		parameters: {method: 'SignOut', username: username, authentication_token: token},
		onSuccess: function(transport){
			resp = transport.responseXML || "no response text";
			currentUsr = null;
			currentPass = null;
			currentToken = null;	
			/* Destoying Cookie */
			cookie = new cookiejar('tienda_virtual');
			cookie.setCookie('username', currentUsr);
			cookie.setCookie('password', currentPass);
			cookie.setCookie('token', currentToken);
			cookie.write();
			//
			var logindiv = document.getElementById("loginLi");
			logindiv.setAttribute("onclick","logInClick();");
			logindiv.innerHTML="Login";	

			var name = document.getElementById("Bienvenida");
			name.innerHTML = "Bienvenid@"
		},
		onFailure: function(){ alert('Problems on Ajax Request') }

  });
}



function logInClick(){

/*	cookie = new cookiejar('tienda virtual');
	currentUsr = cookie.getCookie('username');*/
	//alert("estoy en loginclick");
	if(currentUsr != null){
		return;
	}
	
	displayPopLogIn();
	
}
function logInn(){
	var usernameinput = document.getElementById("usernameImput");
	var pswinput = document.getElementById("passss");
	closePopUpLogIn();
	signin(usernameinput.value,pswinput.value);
	
}
function logOut(){
	
	cookie = new cookiejar('tienda_virtual');
	/*var currentUsrAsd = cookie.getCookie('username') !=;
	var currentTokenAsd = cookie.getCookie('currentToken');*/
		
	if(currentUsr != null){
		signout(currentUsr,currentToken);
	}
	var a = document.getElementById("OrdenesButton");
	a.style.display="none";
	var micuenta = document.getElementById("micuenta")
	micuenta.style.display="none";
	
}
$j(document).ready(function(){
	// checkeamos si hay cookies :3
	cookie = new cookiejar('tienda_virtual');
		
	var usuariotemp = cookie.getCookie('username');
	var passtemp = cookie.getCookie('password');
	var tokentem = cookie.getCookie('token');
	if( usuariotemp != 'null' && passtemp != 'null'){
		signin(usuariotemp,passtemp);
	}
	/*var cookie = new cookiejar("tienda_virtual");
	alert(cookie.getCookie('username'));*/
	
});